package com.umpay.util;

import com.umpay.business.consume.impl.ConsumeNotifyBusinessServiceImpl;
import com.umpay.dict.XmlData;
import com.umpay.dict.XmlData4Mer;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URLEncoder;
import java.util.*;

/**
 * @description P2P公共校验类
 * @author hemz
 * @date 2014-9-15 14:20:31
 * @version V1.0
 */
public class NotifyMerUtil {

	public static final Logger log = LogManager.getLogger(ConsumeNotifyBusinessServiceImpl.class);
	
	
	@Autowired
	private SignatureAuthUtil signatureAuthUtil;
	
	/**
	 * 组装返回签名参数
	 */
	public String doRetUrl(Map<String,Object> resMap, String retUrl, String backRules)throws Exception{
		String param = assMerRes(resMap, "&", backRules);
		/**判断前端业务传递的url是否已经问号*/
		if(retUrl.contains("?")){
			retUrl = retUrl + "&"+ param;
		}else{
			retUrl = retUrl + "?"+ param;
		}
		log.info("retUrl=" + retUrl);
		return retUrl;
	}
	
	/**
	 * <br>description : 组装返回给商户的字段（多余字段拦截、字段值转换）
	 * @param backMap
	 * @return
	 * @author      xiatian
	 * @version     1.0
	 * @date        May 14, 20139:11:56 PM
	 */
	public  String assMerRes(Map<String, Object> retMap, String separator, String backRules) throws Exception{
		Map<String,Object> backMap = new HashMap<String,Object>();
		/**配置必须返回给商户的数据*/
		String strBackRule = StringUtils.trim(PropertiesUtil.getBusiStrValue(backRules,""));
		StringTokenizer st = new StringTokenizer(strBackRule,",");
		while(st.hasMoreTokens()){
			String s = StringUtils.trim(st.nextToken());
			if(XmlData.SIGNTYPE.equals(s)){
				backMap.put(XmlData.SIGNTYPE, "RSA");
			}else if(XmlData.VERSION.equals(s)){
				backMap.put(XmlData.VERSION, "4.0");
			}else if(StringUtils.isNotEmpty(StringUtils.trim(retMap.get(s)))){
				backMap.put(s, StringUtils.trim(retMap.get(s)));
			}
		}
		
		Map<String,String> backConMap = ContrastMapUtil.getBackConMap();  			//获得后台字段名与传递给商户参数名的对应关系
		Map<String, Object> tmp = backMap;
		backMap = new HashMap<String, Object>(backMap.size());
		Iterator<Map.Entry<String, Object>> it = tmp.entrySet().iterator();                   
		while(it.hasNext()){
			Map.Entry<String, Object> entry = it.next();
			if(StringUtils.isEmpty(backConMap.get(entry.getKey()))){                       //进行字段转换
				log.debug(String.format("在后台字段与商户传递参数对应过程中，%s字段没有对应关系",entry.getKey())); 
				backMap.put(entry.getKey(), entry.getValue());
			}else{
				backMap.put(backConMap.get(entry.getKey()), entry.getValue());
			}
		}
		tmp.clear();
		tmp = null;
		
		String[] keySet = (String[])backMap.keySet().toArray(new String[backMap.size()]);   //获取返回给商户的字段集合
		StringBuilder signstr = new StringBuilder("");
		StringBuilder retStr = new StringBuilder("");
		Arrays.sort(keySet);                                                               	//对字段进行排序
		
		for(String key : keySet){
			String value = StringUtils.trim(backMap.get(key));
//			value = URLEncoder.encode(value, "UTF-8");
			if(XmlData.SIGN.equals(key) || XmlData.NOTIFYDATA.equals(key))                  //后台传递sign、notifyData字段不返回给商户
				continue;
			retStr.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append(separator);                       //组装返回给商户的字段
			if(!XmlData4Mer.SIGN_TYPE.equals(key)){                                     				//signType字段不参与签名，故不参与组装签名字符串
				signstr.append(key).append("=").append(value).append(separator);
			}
		}
		String str = signstr.substring(0, signstr.length()-1);                           	//获得返回给商户的数据的明文
		log.info(String.format("平台获得后台返回给商户信息加密组装的明文为：%s" ,str));
		String ret = retStr.substring(0,retStr.length()-1);                                //进行字符串截取(最后一位多"&"字符)
		log.info(String.format("返回给商户的数据明文为：%s",ret));
		String signStr = signatureAuthUtil.signMsg(str);                                                   //对明文串进行签名
		signStr = URLEncoder.encode(signStr, "UTF-8");
		String wholeStr = String.format("%s%ssign=%s", ret,separator,signStr);							//获取返回的商户的完整字符串
		log.info(String.format("平台返回给商户的最终数据为：%s",wholeStr));
		return wholeStr;
	}
}
